<template>
  <div>
    <div class="backgroundset">
      <el-table
        ref="multipleTable"
        :data="tasklist"
        tooltip-effect="dark"
        style="width: 100%"
        border
        stripe
        @selection-change="handleSelectionChange"
        :header-cell-style="{
          background: '#D8E4F0',
          color: '#2A303B',
          fontWeight: '500',
        }"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column align="center" label="题组">
          <template slot-scope="scope">
            <div>{{ scope.row.questionGroupName }}</div>
            <div>{{ scope.row.questionNumbers || "-" }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="题型 ">
          <template slot-scope="scope">
            {{ scope.row.questionTypeName || "-" }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="多评轮次">
          <template slot-scope="scope">
            <el-link
              type="primary"
              @click="rowreviewrounds(scope.row.id, scope.row.reviewRounds)"
              >{{
                scope.row.reviewRounds == 1
                  ? "一评"
                  : scope.row.reviewRounds == 2
                  ? "二评"
                  : "-"
              }}</el-link
            >
          </template>
        </el-table-column>
        <el-table-column align="center" label="多评阈值">
          <template slot-scope="scope">
            {{ scope.row.multiReviewThreshold || "-" }}
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="仲裁设置">
                <template slot-scope="scope">
                    {{ scope.row.createdTime ? scope.row.createdTime : '-' }}
                </template>
                </el-table-column> -->
        <el-table-column align="center" label="剩余任务">
          <template slot-scope="scope">
            {{ scope.row.remainingCount ? scope.row.remainingCount : "-" }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="拟分配">
          <template slot-scope="scope">
            {{ scope.row.assignedCount ? scope.row.assignedCount : "-" }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="已创建">
          <template slot-scope="scope">
            {{ scope.row.createdCount ? scope.row.createdCount : "-" }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="题组分配方式">
          <template slot-scope="scope">
            <div
              @click="questionGrouptype(scope.row.id, scope.$index)"
              style="cursor: pointer"
            >
              <span class="autoquestion" v-if="scope.row.assignmentType == 1"
                >自动分题</span
              >
              <span class="avgquestion" v-if="scope.row.assignmentType == 2"
                >平均分题</span
              >
              <span
                class="efficiencyquestion"
                v-if="scope.row.assignmentType == 3"
                >效率分题</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="评阅分配">
          <template slot-scope="scope">
            <span
              v-if="scope.row.taskStatus == 0 && scope.row.totalSchools != null"
              >参与分配共{{
                scope.row.totalSchools ? scope.row.totalSchools : "-"
              }}校</span
            >
            <span v-if="scope.row.taskStatus == 1"
              >已启用 共{{
                scope.row.totalSchools ? scope.row.totalSchools : "-"
              }}校</span
            >
            <b
              class="taskredborder"
              v-if="
                scope.row.taskStatus == null && scope.row.totalSchools == null
              "
              >未分配</b
            >
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="160">
          <template slot-scope="scope">
            <el-link type="primary" @click="taskshooltap(scope.row)"
              >分配详情</el-link
            >
            <!-- <el-link
              type="info"
              v-if="scope.row.taskStatus == 1"
              :underline="false"
              >启用中</el-link
            > -->
            <!-- <el-link
              type="primary"
              @click="Enabletab(scope.row.id)"
              v-if="scope.row.taskStatus == 0 || scope.row.taskStatus == null"
              >启用</el-link
            > -->
            <!-- <el-link
              type="success"
              v-if="scope.row.taskStatus == 2"
              :underline="false"
              >完成</el-link
            > -->
            <!-- <el-link
              type="danger"
              v-if="scope.row.taskStatus != 1"
              @click="singleClear(scope.row.id)"
              >清空</el-link
            > -->
          </template>
        </el-table-column>
      </el-table>
      <div class="page-bottom">
        <div class="examfooter">
          <div class="examFootercontent">
            <el-button
              type="primary"
              style="margin-top: 7px"
              @click="taskwaytap"
              :loading="yjfpLoading"
              :disabled="statusReviewing"
              >{{ yjfpLoading ? "分配中" : "一键分配" }}</el-button
            >
            <el-button type="primary" style="margin-top: 7px" @click="refresh"
              >刷新</el-button
            >
            <!-- <el-button
              type="primary"
              style="margin-top: 7px"
              @click="EnabletabAll"
              >启用全部任务</el-button
            > -->
            <el-button
              type="primary"
              style="margin-top: 7px"
              @click="taskquestiontype"
              >修改分题模式</el-button
            >
            <el-button type="primary" style="margin-top: 7px" @click="lqtz"
              >拉取题组</el-button
            >
            <el-button
              :loading="statusReviewing"
              type="primary"
              @click="changeReviewStatus"
              style="margin-top: 7px"
              :disabled="yjfpLoading"
              >{{ statusReviewing ? "变更中" : "变更评阅状态" }}</el-button
            >
            <el-button
              type="primary"
              :loading="messageLoading"
              @click="sendMessage"
              style="margin-top: 7px"
              >{{ messageLoading ? "消息推送中..." : "消息推送" }}</el-button
            >
            <!-- <el-button style="background:#1A48DB;color:#fff;margin-left:20px;border-color:#1A48DB;margin-top:10px;">多评规则</el-button> -->
            <!-- <el-button
              type="danger"
              style="margin-top: 7px"
              @click="clearAllquestion"
              >清空任务</el-button
            > -->
          </div>
        </div>
      </div>
    </div>
    <!-- 分配学校 -->
    <Allocateschools
      v-if="allocateschoolishow"
      :allocateschoolishow="allocateschoolishow"
      @alltaskschoolSureemit="alltaskschoolSureemit"
      :taskschoollist="taskschoollist"
      :questionCon="questionCon"
    ></Allocateschools>
    <!-- 分配模式 -->
    <Taskway
      v-if="taskwayishow"
      :taskwayishow="taskwayishow"
      @taskwaySureemit="taskwaySureemit"
      @tasktypechange="tasktypechange"
      :questiongroup="questiongroup"
      :tasklist="tasklist"
      :multipleSelection="multipleSelection"
    ></Taskway>

    <!-- 变更评阅状态-弹框 -->
    <el-dialog
      title="变更评阅状态"
      :visible.sync="changeReviewStatusVisible"
      @close="changeReviewStatusVisibleCancel"
      width="600px"
    >
      <el-form>
        <el-form-item label="选择评阅状态" label-width="120px">
          <el-select
            v-model="reReviewRange"
            placeholder="请选择评阅状态"
            style="width: 100%"
          >
            <el-option :value="1" label="开始评阅"></el-option>
            <el-option :value="2" label="暂停评阅"></el-option>
            <el-option :value="3" label="结束评阅"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="changeReviewStatusVisibleSub()"
          >确认变更</el-button
        >
        <el-button @click="changeReviewStatusVisibleCancel()">返 回</el-button>
      </div>
    </el-dialog>

    <!-- 消息推送-弹框 -->
    <el-dialog
      title="消息推送"
      :visible.sync="sendMessageVisible"
      @close="sendMessageVisibleCancel"
      width="600px"
    >
      <el-form
        ref="xxtsForm"
        :model="xxtsForm"
        :rules="xxtsRules"
        label-width="120px"
      >
        <el-form-item label="选择发送模板" prop="sendMessageRange">
          <el-select
            v-model="xxtsForm.sendMessageRange"
            placeholder="选择发送模板"
            style="width: 100%"
          >
            <el-option :value="1" label="开启阅卷"></el-option>
            <el-option :value="2" label="后传释放阅卷"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="管理员授权密码" prop="password">
          <el-input
            v-model="xxtsForm.password"
            type="password"
            placeholder="请输入管理员授权密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="sendMessageVisibleSub()"
          :loading="messageLoading"
          >确 认</el-button
        >
        <el-button @click="sendMessageVisibleCancel()">返 回</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Allocateschools from "../../../components/task/allocateschools.vue";
import Taskway from "../../../components/task/taskway.vue";
import {
  oneclickAllocation,
  singQuestionassignment,
  batchclickAllocation,
  deleteQuestion,
  syncQuestionGroup,
  getOpsStatus,
} from "../../../api/task/task.js";
import { updatePyjdStatusAll, sendMessage } from "@/api/xmgl/pyjd";
import { checkPassword } from "@/api/common";
export default {
  props: {
    pyjdData: {},
    tasklist: {
      type: Array,
      default: () => [],
    },
    examsubjectid: {
      type: Number,
      default: () => "",
    },
  },
  components: {
    Allocateschools,
    Taskway,
  },
  data() {
    return {
      multipleSelection: [],
      allocateschoolishow: false,
      taskwayishow: false,
      questiongroup: {
        siglequestiontype: 1,
        questionid: 0,
        questionindex: 0,
      },
      tasktype: 0,
      taskschoollist: [],
      questionCon: {},

      yjfpLoading: false,
      statusReviewing: false,
      messageLoading: false,

      changeReviewStatusVisible: false,
      // 重评范围
      reReviewRange: "",

      // new
      sendMessageVisible: undefined, //消息推送-选择发送模板

      xxtsForm: {
        sendMessageRange: undefined,
        password: "",
      },
      xxtsRules: {
        sendMessageRange: [
          { required: true, message: "请选择发送模板", trigger: "change" },
        ],
        password: [
          { required: true, message: "请输入管理员授权密码", trigger: "blur" },
        ],
      },

      timer: null,
    };
  },
  watch: {
    examsubjectid: {
      handler(newVal, oldVal) {
        this.endTime();
        this.getStatus();
      },
    },
  },
  created() {
    this.getStatus();
  },
  methods: {
    getStatus() {
      getOpsStatus({ subjectId: this.examsubjectid }).then((res) => {
        if (
          res.data.assignmentStatus == 1 &&
          res.data.syncQuestionStatus == 1 &&
          this.timer
        ) {
          this.yjfpLoading = false;
          this.statusReviewing = false;
          this.refresh();
          this.endTime();
        } else if (res.data.syncQuestionStatus == 0 && !this.timer) {
          this.statusReviewing = true;
          this.startTime();
        } else if (res.data.assignmentStatus == 0 && !this.timer) {
          this.yjfpLoading = true;
          this.startTime();
        }
      });
    },
    startTime() {
      this.timer = setInterval(() => {
        this.getStatus();
      }, 5000);
    },
    endTime() {
      this.yjfpLoading = false;
      this.statusReviewing = false;
      clearInterval(this.timer);
      this.timer = null;
    },
    changeReviewStatus() {
      this.reReviewRange =
        this.pyjdData.reviewStatus != "0" ? this.pyjdData.reviewStatus : "";
      this.changeReviewStatusVisible = true;
    },
    sendMessage() {
      this.sendMessageVisible = true;
    },
    // 变更评阅状态-提交
    changeReviewStatusVisibleSub() {
      if (!this.reReviewRange) {
        this.$modal.alertError("请选择评阅状态");
        return;
      }

      let obj = {
        subjectId: this.examsubjectid,
        reviewStatus: this.reReviewRange,
      };
      this.changeReviewStatusVisible = false;
      this.statusReviewing = true;

      let reReviewRange = this.reReviewRange;

      updatePyjdStatusAll(obj)
        .then((res) => {
          if (res.code === 200) {
            if (reReviewRange == 1) {
              this.startTime();
            } else if (reReviewRange != 1) {
               this.statusReviewing = false;
              this.refresh();
              this.$message.success("评阅状态已全部变更！");
            }
          }
        })
        .catch((err) => {
          setTimeout(() => {
            this.statusReviewing = false;
          }, 500);
          this.$message.error("评阅状态变更失败！");
        })
    },
    // 变更评阅状态-取消
    changeReviewStatusVisibleCancel() {
      this.changeReviewStatusVisible = false;
      this.reReviewRange = undefined;
    },

    sendMessageVisibleSub() {
      // if (!this.sendMessageRange) {
      //   this.$message.error("请选择发送模板");
      //   return false;
      // }
      this.$refs.xxtsForm.validate((valid) => {
        if (valid) {
          this.messageLoading = true;
          checkPassword({
            password: this.xxtsForm.password,
            schoolId: this.$store.state.user.deptId,
          })
            .then((res) => {
              let obj = {
                messageType: this.xxtsForm.sendMessageRange,
                examSubjectId: this.examsubjectid,
              };
              sendMessage(obj)
                .then((res) => {
                  if (res.code === 200) {
                    this.$message.success("发送成功");
                    this.sendMessageVisible = false;
                  }
                })
                .finally(() => {
                  this.messageLoading = false;
                });
            })
            .catch(() => {
              this.messageLoading = false;
            });
        }
      });
    },
    sendMessageVisibleCancel() {
      this.sendMessageVisible = false;
      this.$refs.xxtsForm.resetFields();
    },

    //分配模式
    questionGrouptype(id, index) {
      this.questiongroup.questionid = id;
      this.questiongroup.siglequestiontype = 1;
      this.questiongroup.questionindex = index;
      this.taskwayishow = true;
    },
    //批量分配模式
    taskquestiontype() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请选择要分配的任务",
          type: "warning",
        });
        return;
      }
      this.questiongroup.siglequestiontype = 2;
      this.taskwayishow = true;
    },
    //二平
    rowreviewrounds(id, reviewRounds) {
      let obj;
      this.$modal
        .confirm("确认修改多评轮次，修改后需要进行重新分配任务")
        .then(() => {
          if (reviewRounds == 1) {
            obj = {
              id: id,
              reviewRounds: 2,
            };
          } else {
            obj = {
              id: id,
              reviewRounds: 1,
            };
          }
          singQuestionassignment(obj).then((res) => {
            if (res.code == 200) {
              this.$emit("rowreviewrounds", id);
              this.$message({
                message: "修改成功",
                type: "success",
              });
            }
          });
        });
    },
    //启用未启用
    Enabletab(id) {
      let obj = {
        id: id,
        taskStatus: 1,
      };
      singQuestionassignment(obj).then((res) => {
        if (res.code == 200) {
          this.$emit("rowreviewrounds", id);
          this.$message({
            message: "启用成功",
            type: "success",
          });
        }
      });
    },
    //启用全部任务
    EnabletabAll() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请选择要启用的任务",
          type: "warning",
        });
        return;
      }
      let ids = this.multipleSelection.map((item) => {
        return {
          id: item.id,
          taskStatus: 1,
        };
      });
      batchclickAllocation(ids).then((res) => {
        if (res.code == 200) {
          this.$emit("taskwaytap", 1);
          this.$message({
            message: "启用成功",
            type: "success",
          });
        }
      });
    },
    tasktypechange(val) {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请选择分配方式",
          type: "warning",
        });
        return;
      }
      let ids = this.multipleSelection.map((item) => {
        return {
          id: item.id,
          assignmentType: val,
        };
      });
      batchclickAllocation(ids).then((res) => {
        if (res.code == 200) {
          this.taskwayishow = false;
          this.$emit("rowreviewrounds", id);
          this.$message({
            message: "修改分题模式成功",
            type: "success",
          });
        }
      });
    },
    //一键分配
    taskwaytap() {
      this.$modal
        .confirm("一键分配后模板将不能修改，是否确认分配任务")
        .then(() => {
          let obj = {
            examId: this.examsubjectid,
          };
          this.yjfpLoading = true;
          oneclickAllocation(obj)
            .then((res) => {
              if (res.code == 200) {
                this.startTime();
              }
            })
            .catch(() => {
              this.yjfpLoading = false;
            });
        });
    },
    alltaskschoolSureemit(data) {
      this.allocateschoolishow = false;
      if (data == 1) {
        this.addmodelsubject(this.xmxx.id);
      }
    },
    taskwaySureemit(data) {
      this.taskwayishow = false;
      if (data == 1) {
        this.$emit("taskwaytap", 1);
      }
    },
    //分配学校
    taskshooltap(con) {
      this.allocateschoolishow = true;
      this.questionCon = con;
      // let obj={
      //     id:con.id
      // }
      // Allocateschoolslist(obj).then(res=>{
      //     if(res.code==200){
      //         this.taskschoollist = res.rows.map(item=>{
      //             return {
      //                 ...item,
      //                 isDisabled:true,
      //                 disassemblytask:item.totalAssignments
      //             }
      //         })
      //     }
      // })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    refresh() {
      this.$emit("refresh");
    },
    // 单个清空
    singleClear(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteQuestion([id]).then((res) => {
            if (res.code == 200) {
              this.$emit("refresh");
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //清空全部
    clearAllquestion() {
      // 1. 检查是否选中任务
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请选择要清空的任务");
        return;
      }

      // 2. 检查任务状态是否全部为未启用（taskStatus=1）
      const hasInvalidTask = this.multipleSelection.some(
        (item) => item.taskStatus == 1
      );
      if (hasInvalidTask) {
        this.$message.warning("请选择未启用的任务");
        return;
      }

      // 3. 提取所有任务的 id
      const ids = this.multipleSelection.map((item) => item.id);

      // 4. 弹出确认框
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 5. 调用删除接口
          deleteQuestion(ids).then((res) => {
            if (res.code === 200) {
              this.$emit("refresh"); // 刷新数据
              this.$message.success("删除成功!");
            }
          });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    lqtz() {
      syncQuestionGroup({
        examId: this.examsubjectid,
      }).then((res) => {
        this.$message.success("操作成功!");
        this.$emit("refresh"); // 刷新数据
      });
    },
  },
  beforeDestroy() {
    if (this.timer) {
      this.endTime();
    }
  },
};
</script>

<style scoped>
.backgroundset {
  padding: 0 15px 15px 15px;
  background: #fff;
}
.custom-table {
  width: 100%;
  border: 1px solid rgba(216, 228, 240, 0.34);
  border-right: none;
  border-bottom: none;
}
/* 自定义表格内部元素的样式 */
.custom-table >>> .el-table__header-wrapper th {
  background-color: #e8f0fa;
  height: 42px;
  padding: 0;
  text-align: center;
  font-weight: normal;
}
.custom-table >>> .el-table th.el-table__cell.is-leaf,
.custom-table >>> .el-table td.el-table__cell {
  border-bottom: none;
}
.custom-table >>> .el-table__row td {
  height: 42px;
  padding: 0;
  text-align: center;
  border-right: solid 1px rgba(216, 228, 240, 0.5);
  font-size: 14px;
}
.el-table .warning-row {
  background: #ffffff;
}
.el-table .success-row {
  background: #d8e4f0;
}
.el-table .el-table__cell {
  padding: 8px 0;
}
.examfooter {
  width: 100%;
  height: 54px;
  left: 0;
  bottom: 0;
}
.examFootercontent {
  margin: 0 auto;
  display: flex;
  align-items: center;
}
.examFootercontent .totaldata {
  font-size: 14px;
}
.examFootercontent .totaldata i {
  display: inline-block;
  color: #295cff;
  font-style: normal;
  line-height: 54px;
  padding: 0 3px;
}
.taskredborder {
  display: inline-block;
  width: 62px;
  height: 22px;
  background: #ec555a0f;
  border: 1px solid #ec555a80;
  border-radius: 4px;
  color: #ec555a;
  font-size: 14px;
  font-weight: normal;
}
.scopednr b {
  font-weight: normal;
  margin: 0 10px;
  color: #1a48db;
  text-decoration: underline;
  cursor: pointer;
}
.scopednr b.hover {
  color: #ec555a;
}
.autoquestion,
.avgquestion,
.efficiencyquestion {
  display: inline-block;
  width: 76px;
  height: 22px;
  font-size: 14px;
  border-radius: 4px;
}
.autoquestion {
  background: #1a48db0f;
  border: 1px solid #1a48db80;
  color: #1a48db;
}
.avgquestion {
  background: #2f44890f;
  border: 1px solid #2f448980;
  color: #2f4489;
}
.efficiencyquestion {
  background: #ca61270f;
  border: 1px solid #ca612780;
  color: #ca6127;
}
</style>